package main

import (
	"github.com/asaskevich/EventBus"
	"time"

	//"context"
	"fmt"
)

/*func calculator(a int, b int) {
	fmt.Printf("%d\n", a + b)
	time.Sleep(5 * time.Second)
	print("ok")
}*/
func calculator() {
	print("tt")
	time.Sleep(5 * time.Second)
	print("ok")
}

func calculators(a int, b int) {
	fmt.Printf("%d\n", b-a)
}

func TestSubscribeAsync() {
	results := make(chan int)

	bus := EventBus.New()
	bus.SubscribeAsync("topic", func(a int, out chan<- int) {
		out <- a
	}, false)

	bus.Publish("topic", 1, results)
	bus.Publish("topic", 2, results)

	numResults := 0

	go func() {
		for _ = range results {
			numResults++
		}
	}()

	bus.WaitAsync()

	time.Sleep(10 * time.Millisecond)
	print(numResults)
}

func TestSubscribeAsyncTransactional() {
	results := make([]int, 0)

	bus := EventBus.New()
	bus.SubscribeAsync("topic", func(a int, out *[]int, dur string) {
		sleep, _ := time.ParseDuration(dur)
		time.Sleep(sleep)
		*out = append(*out, a)
	}, true)

	bus.Publish("topic", 1, &results, "1s")
	bus.Publish("topic", 2, &results, "0s")

	bus.WaitAsync()

	print(results[0])
	print(results[1])

}

func main() {

	TestSubscribeAsyncTransactional()
	return

	bus := EventBus.New()
	bus.SubscribeAsync("main:slow_calculator", calculator, true)
	bus.Subscribe("main:slow_calculators", calculators)
	//bus.SubscribeAsync("main:slow_calculator", calculator,true)

	bus.Publish("main:slow_calculator")
	bus.Publish("main:slow_calculator")
	bus.Publish("main:slow_calculator")
	//bus.Publish("main:slow_calculators",10,20)

	fmt.Println("start: do some stuff while waiting for a result")
	fmt.Println("end: do some stuff while waiting for a result")

	bus.WaitAsync() // wait for all async callbacks to complete

	fmt.Println("do some stuff after waiting for result")

	/*bus := EventBus.New();
	bus.SubscribeAsync("main:calculator", calculator,false);
	bus.SubscribeAsync("main:calculators", calculators,false);

	bus.Publish("main:calculator", 20, 40);
	bus.Publish("main:calculator", 20, 40);
	//bus.Unsubscribe("main:calculator", calculator);
	bus.Publish("main:calculators", 20, 40);
	//bus.Subscribe("main:calculator", calculator);
	//bus.Publish("main:calculator", 20, 40);
	time.Sleep(30 * time.Second)*/

	/*cmd := exec.CommandContext(context.TODO(), "cmd","echo hello")

	// 执行并捕获输出
	output, err := cmd.CombinedOutput()
	print(output)

	config := clientv3.Config{
		Endpoints:[]string{"10.2.111.241:2379","10.2.111.241:2380"},
		DialTimeout:10*time.Second,
	}
	client,err := clientv3.New(config)
	if err != nil {
		panic(err)
	}
	defer client.Close()*/
}
